/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.swing.JOptionPane;

/**
 *
 * @author fumio
 */
public class Dao {

    private static EntityManagerFactory emf = null;
    private static EntityManager em = null;

    private static EntityManager getEm() {
        if (em == null) {

            emf = Persistence.createEntityManagerFactory("HairSystemPU");
            em = emf.createEntityManager();
        }
        return em;


    }

    public static void StartTransaction() {
        try {

            getEm().getTransaction().begin();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }

    public static void EndTransaction() {
        getEm().getTransaction().commit();
    }

    public static void CancelTransaction() {
        em.getTransaction().rollback();
    }

    public static boolean persist(Object o) {
        boolean salvo = false;
        try {
            StartTransaction();
            getEm().persist(o);
            EndTransaction();
            JOptionPane.showMessageDialog(null, "Registrado Com Sucesso!");
            salvo = true;
        } catch (Exception e) {
            CancelTransaction();
            JOptionPane.showMessageDialog(null, e.getMessage()+" Não Foi Possível Realizar Cadastro");
            salvo = false;
        }
        return salvo;
    }

    public static List select(String sql) {
        Query query = null;
        try {
            query = getEm().createQuery(sql);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        System.out.println(query.getResultList());
        return query.getResultList();
    }

    static boolean remove(Object objeto) {
        boolean remover = true;
        try {

            StartTransaction();
            getEm().remove(objeto);
            EndTransaction();
            remover = true;

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
            CancelTransaction();
            remover = false;
        }

        return remover;
    }
}
